package com.codingvip.stack;

import java.util.Stack;

/**
 * @Author Tony.Han
 * @Created at 2020/4/9 1:59 下午
 * Desc:
 */
public class MinStack {
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    /**
     * initialize your data structure here.
     */
    public static void main(String[] args) {


        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());  // --> 返回 -3.
        minStack.pop();
        System.out.println(minStack.top());      //--> 返回 0.
        System.out.println(minStack.getMin());   //--> 返回 -2.

    }

    Stack<Integer> stack1 = null;
    Stack<Integer> stack2 = null;
    int minNumber = Integer.MAX_VALUE;

    public MinStack() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int x) {
        if (x < minNumber) {
            minNumber = x;
        }
        stack1.push(x);
    }

    public void pop() {
        if (stack1.isEmpty()) {
            return;
        }
        int value = stack1.pop();
        if (value <= minNumber) {
            rePush();
        }
    }

    public void rePush() {
        while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        minNumber = Integer.MAX_VALUE;
        while (!stack2.isEmpty()) {
            push(stack2.pop());
        }
    }

    public int top() {
        if (stack1.isEmpty()) {
            return -1;
        }
        return stack1.peek();
    }

    public int getMin() {
        return minNumber;
    }
}
